package com.tanhua.recommend.msg;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.recommend.pojo.RecommendVideo;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.bson.types.ObjectId;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @description:
 * @author: Administrator
 * @date: Created in 2021/2/27 9:02
 * @version: 0.0.1
 * @modified By:
 */
@Component
@RocketMQMessageListener(topic = "tanhua-video",consumerGroup = "tanhua-video-consumer")
public class VideoMsgConsumer implements RocketMQListener<String> {

    private static final ObjectMapper MAPPER=new ObjectMapper();
    private static final Logger LOGGER= LoggerFactory.getLogger(QuanZiMsgConsumer.class);

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void onMessage(String msg) {
        try {
            JsonNode jsonNode = MAPPER.readTree(msg);
            Integer type = jsonNode.get("type").asInt();
            Long userId = jsonNode.get("userId").asLong();
            Long vid = jsonNode.get("vid").asLong();
            //1-发布小视频 2-点赞小视频 3-取消点赞小视频 4-评论小视频
            RecommendVideo recommendVideo=new RecommendVideo();
            recommendVideo.setDate(System.currentTimeMillis());
            recommendVideo.setId(ObjectId.get());
            recommendVideo.setUserId(userId);
            recommendVideo.setVideoId(vid);
            switch(type){
                case 1:{
                    recommendVideo.setScore(2d);
                    break;
                }
                case 2:{
                    recommendVideo.setScore(5d);
                    break;
                }
                case 3:{
                    recommendVideo.setScore(-5d);
                    break;
                }
                case 4:{
                    recommendVideo.setScore(10d);
                    break;
                }
                default:{
                    recommendVideo.setScore(0d);
                    break;
                }
            }
            //将数据写入mongodb
            String collectionName="recommend_video_"+new DateTime().toString("yyyyMMdd");
            this.mongoTemplate.save(recommendVideo,collectionName);
        } catch (IOException e) {
            LOGGER.error("消息处理失败，msg="+msg,e);
        }
    }
}
